//
//  MTHomeViewController.m
//  ebook
//
//  Created by 吴超飞 on 16/1/14.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "MTHomeViewController.h"
#import "ReaderViewController.h"
#import "EbookNetRequest.h"
#import "Book.h"
#import "MJRefresh.h"
#import "BookcaseView.h"
#import "MBProgressHUD.h"
#import "FmdbAccess.h"
#import "FileManager.h"
#import "UIImageView+WebCache.h"
#import "SearachViewController.h"
#import "MTRate.h"
#import "FeedbackViewController.h"
#import "ReaderGlobalModel.h"
#import "GuestLoginManager.h"
#import "MISAlertController.h"
#import "DownloadManager.h"
#import "BookcaseOprationController.h"
#import "UpdateInfoManager.h"
#import "AppUpdateView.h"
#import "FileManager.h"
#import "AdViewController.h"

#define GDBookCollectionCellID @"BookcaseCell"

@interface MTHomeViewController ()<BookcaseViewDelegate>{
    
    BOOL isFirstIn;
    BOOL isManualRefresh;//第一次进入的刷新或手动刷新,需要提示更新章节数；加入新书进书架的通知处理则不需要提示
}

@property (nonatomic, assign) BOOL isEditing;//是否处于编辑状态

/** 书架数据 */
@property (nonatomic, retain) __block NSMutableArray *books;
@property (nonatomic, retain) BookcaseView *bookcaseView;

@end

@implementation MTHomeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc]init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc]init]];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
 
//    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    AdViewController *adVc = [mainSb instantiateViewControllerWithIdentifier:@"AdViewController"];
//    [self presentViewController:adVc animated:NO completion:^{}];
    
    // 设置顶部工具条
    [self setSearchToolbar];
    [self setEditToolbar];
    isFirstIn = YES;
    
    //读本地（书架、推荐）、显示
    [self getLocalBooksAndLoadView];
    
    [GuestLoginManager autoLogin:^(BOOL issuc) {
        
        [self getMenudata];
        [self getBookcaseSetNowreadWithBook:nil];
    }];
    
    if (![super isNetConnect]) {
        self.navigationItem.title = @"我的书架(未连接)";
    } else {
        self.navigationItem.title = @"我的书架";
    }
    
    [self addNotificationObserver];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self refrehBookcase];
}

-(void)addNotificationObserver{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNewBookIntoCase:) name:kUpdateBookshelfNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeBookInCase:) name:kDelShouldUpdateBookshelfNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDownloadStatus:) name:kFinishOneDownloadTaskNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateReadpercent:) name:kUpdateLocalshelNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLocalBooksAndLoadView) name:kFreshLocalshelNotification object:nil];//重新加载视图
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getLocalBooksAndLoadView) name:kDownloadTaskCancelNotification object:nil];//下载任务被取消时重新加载视图
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refrehBookcase) name:UIApplicationDidBecomeActiveNotification object:nil];//从后台切换到前台时，需要刷新书架
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getlastReadnodeFailed:) name:kGetlastReadnodeFailedNotification object:nil];//阅读时上次
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adViewRemove) name:kAdviewRemoveNotification object:nil];
}

-(void)adViewRemove{
    
    [self infoBookUpdata];
    if(((AppDelegate *)[UIApplication sharedApplication].delegate).checkver){//需要检查应用更新
        [AppUpdateView showAppUpdateInController:self];
        ((AppDelegate *)[UIApplication sharedApplication].delegate).checkver = NO;
    }
}

-(void)getMenudata{
    
    [EbookNetRequest getStoreMenuSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:dict] forKey:KBookCityData];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[DownloadManager shareInstance] restoreDownload];
    } failed:^(int stateCode, NSString *failMsg) {
    }];
}

//提示更新
-(void)infoBookUpdata{
    
    if([[[NSUserDefaults standardUserDefaults] objectForKey:kLauchTimes] integerValue]>1&&isFirstIn){//新安装不提示更新
        isFirstIn = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            isManualRefresh = YES;
            [self getLocalBooksData];
        });
    }
}

-(void)refrehBookcase{
    
    double lasttime = [[NSUserDefaults standardUserDefaults] doubleForKey:kLastRefreshBookcaseTime];
    double interval = [[NSDate date] timeIntervalSince1970]-lasttime;
    MTLog(@"距上次刷新书架interval:%fs",interval);
    if (lasttime>0 && interval > 20*60) {//距离上次刷新时间超过20分钟，刷新书架
        [self getBookcaseSetNowreadWithBook:nil];
    }
}

#pragma mark - 时时监听网络状态
- (void)coreNetworkChangeNoti:(NSNotification *)noti
{
    CoreNetWorkStatus currentStatu = [CoreStatus currentNetWorkStatus];
    
    MTLog(@"coreNetworkChangeNoti:::%d", currentStatu);
    self.navigationItem.title = [super isNetConnect]? @"我的书架":@"我的书架(未连接)";
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.isEditing = NO;
}

#pragma mark - 通知
//下载通知
- (void)updateDownloadStatus:(NSNotification *)noti {
    
    NSDictionary *dic = noti.object;
    [self.bookcaseView updateBookcaseDownstatus:dic];
}

//更新阅读百分比通知
-(void)updateReadpercent:(NSNotification *)noti {
    //读书百分比写入数据库完成后的通知
    Book *book = (Book *)noti.object;
    [self.bookcaseView updateBookcaseReadpercent:book];//全单元格视图阅读后只需独立更新阅读百分比
}

//新书加入书架通知
-(void)addNewBookIntoCase:(NSNotification *)noti {
    
    isManualRefresh = NO;
    NSString *bookid = noti.object;
    [self getBookcaseSetNowreadWithBook:bookid];
}

//书架移除通知
-(void)removeBookInCase:(NSNotification *)noti{
    
    isManualRefresh = NO;
    NSString *bookid = noti.object;
    if (bookid && [bookid intValue]>0)
        if([[FmdbAccess shareModel] removeBookcase:bookid])
            [self getBookcaseSetNowreadWithBook:bookid];
}

-(void)getlastReadnodeFailed:(NSNotification *)noti {
    
    Book *book = noti.object;
    NSString *msg = [NSString stringWithFormat:@"获取《%@》上次阅读位置失败，请手动定位",book.bookname];
    [ToastView showMsg:msg inView:self.view isCenter:YES];
}

#pragma mark - NavigationItem
- (void)setSearchToolbar
{
    UIBarButtonItem *searchBar = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchBtnClick:)];
    searchBar.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.rightBarButtonItem = searchBar;
}

- (void)searchBtnClick:(id)sender{
    
    self.navigationItem.leftBarButtonItem.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationItem.leftBarButtonItem.enabled = YES;
        MTLog(@"enable YES:%f",[[NSDate date] timeIntervalSince1970]);
    });
    
    SearachViewController *searchVc = [[SearachViewController alloc] init];
    [self.navigationController pushViewController:searchVc animated:YES];
}

-(void)setEditToolbar{
    
    UIBarButtonItem *eidtItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bookcase_edit"] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick:)];
    eidtItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = eidtItem;
}

-(void)rightBarButtonItemClick:(UIBarButtonItem *)item {
    
    self.isEditing = !self.isEditing;
    self.bookcaseView.isEdit = _isEditing;
}

-(void)setIsEditing:(BOOL)isEditing{
    
    _isEditing = isEditing;
    self.navigationItem.leftBarButtonItem.image =  isEditing?[UIImage imageNamed:@"bookcase_finish"]:[UIImage imageNamed:@"bookcase_edit"];
}

#pragma mark - 数据获取

-(Book *)book:(Book *)book inBooksArray:(NSArray *)arary{
    
    Book *reBook=nil;
    for (Book *book0 in arary) {
        if ([book0.bookid integerValue] == [book.bookid integerValue]){
            reBook = book0;
            break;
        }
    }
    return reBook;
}

//获取本地数据并刷新界面
- (void)getLocalBooksAndLoadView {
    
    [self getLocalBooksData];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self loadBookcaseView];
    });
}

//获取本地书架数据,根据书架数据提示更新
-(void)getLocalBooksData{
    if(!_books)
        _books = [[NSMutableArray alloc] init];
    [_books removeAllObjects];
    
    __unsafe_unretained typeof(self) weakSelf = self;
    //获取书架数据
    [[FmdbAccess shareModel] getBookcases:^(NSMutableArray *casebooks) {
        __strong __typeof(self) strongSelf = weakSelf;
        for (Book *book in casebooks) {
//            if([book.display intValue]!=1)continue;
            //如果本地存在章节列表则取本地章节列表中的总数，以便做准确的更新提示
            NSString *lastChaptercountAcrFile = book.lasthaptercount;
            NSArray *localArray = [FileManager readChapterlist:book];
            if(localArray && localArray.count>0)lastChaptercountAcrFile = [NSString stringWithFormat:@"%d",(int)localArray.count];
            
            Book *b = [strongSelf book:book inBooksArray:self->_books];
            book.isrecommend = NO;
            book.lasthaptercount = lastChaptercountAcrFile;
            if (b) {
                [self->_books replaceObjectAtIndex:[self->_books indexOfObject:b] withObject:book];
            } else {
                [self->_books addObject:book];
            }
        }
    }];
    
    if(isManualRefresh){//提示更新
        [[UpdateInfoManager shareInstance] showUpdateInfo:_books inView:self.view];
        isManualRefresh = NO;
    }
}

//获取书架
-(void)getBookcase{
    
    isManualRefresh=YES;
    [self getBookcaseSetNowreadWithBook:nil];
}

//bookid!=nil，设置这本书的阅读时间为当前
-(void)getBookcaseSetNowreadWithBook:(NSString *)bookid{
    
    __unsafe_unretained typeof(self) weakSelf = self;
    [BookcaseOprationController bookcaseSuccess:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        __strong __typeof(self) strongSelf = weakSelf;
        [[NSUserDefaults standardUserDefaults] setDouble:[[NSDate date] timeIntervalSince1970] forKey:kLastRefreshBookcaseTime];
        [strongSelf.bookcaseView.mj_header endRefreshing];
        NSArray *books = dict[@"data"][@"books"];
        
        NSMutableArray *bArray = [NSMutableArray array];
        for (NSDictionary *dic in books) {
            Book *book = [[Book alloc]initWithDictionary:dic];
            if(bookid&&[book.bookid integerValue]==[bookid integerValue])
                book.readingtime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
                [bArray addObject:book];
        }
        [ReaderGlobalModel shareModel].bookshelf = bArray;
        
        if ([[FmdbAccess shareModel] addBookcase:bArray]||bookid) {//bookid!=nil 此书刚加入了书架，需刷新
            [strongSelf getLocalBooksAndLoadView];
        }else{
            [self getLocalBooksData];
        }
    } failed:^(int stateCode, NSString *failMsg) {
        
        [weakSelf.bookcaseView.mj_header endRefreshing];
    }];
}

-(void)loadBookcaseView{
    
    CGFloat y = 0;
    CGFloat width = MTScreenW;
    CGFloat height = MTScreenH-SafeAreaTopHeight-SafeAreaBTabbarHeight;
    CGRect frame = CGRectMake(0, y, width, height);
    if (_books) {
        [self deallocBookCaseView];
    }
    _bookcaseView = [[BookcaseView alloc] initWithBookArray:_books frame:frame];
    _bookcaseView.bookDelegate = self;
    [self.view addSubview:_bookcaseView];
    
    MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(getBookcase)];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:@"下拉更新" forState:MJRefreshStateIdle];
    [header setTitle:@"松手更新" forState:MJRefreshStatePulling];
    [header setTitle:@"检查更新中" forState:MJRefreshStateRefreshing];
    [header setTitle:@"所有书籍均是最新" forState:MJRefreshStateNoMoreData]; // @todo
    header.stateLabel.textColor = MTConfigColor(@"MTMJRefresh_headerStateLabelText_Color");
    header.stateLabel.font = [UIFont systemFontOfSize:12];
    header.backgroundColor = MTConfigColor(@"MTMJRefresh_headerBg_Color");
    header.height = 38;
    
    _bookcaseView.backgroundColor = MTConfigColor(@"MTBookshelf_bookcaseViewBg_Color");
    self.bookcaseView.mj_header = header;
    self.isEditing = NO;
}

- (void)deallocBookCaseView
{
    if(_bookcaseView){
        [_bookcaseView removeFromSuperview];
        _bookcaseView = nil;
    }
}

#pragma mark - BookcaseCellDelegate
-(void)bookcaseView:(BookcaseView *)view deleteBook:(Book *)book complete:(void(^)(BOOL suc))complete{
    
    MBProgressHUD *_HUD = [[MBProgressHUD alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    _HUD.labelText = @"删除中...";
    [_HUD show:YES];
    [self.view addSubview:_HUD];
    __unsafe_unretained typeof(self) weakSelf = self;
    [BookcaseOprationController removeBookcase:book.bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        
        [FileManager removeLocalBook:book.bookid];//删除本地缓存
        [[FmdbAccess shareModel] removeBookcase:book.bookid];//删除表中一本书的数据
        [[FmdbAccess shareModel] removeReadBooknode:book.bookid];
        if([[[DownloadManager shareInstance] currentDownload].book.bookid integerValue]==[book.bookid integerValue])//如果该本书正在下载，则需取消下载
            [[NSNotificationCenter defaultCenter] postNotificationName:kDownloadTaskCancelShouldDeleteQueueNotification object:book];
        if(complete)complete(YES);
        [_HUD removeFromSuperview];
        
        //移除书架里的书后刷新书架
        [weakSelf.books enumerateObjectsUsingBlock:^(Book *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.bookid intValue] == [book.bookid intValue]) {
                [weakSelf.books removeObject:obj];
                *stop = YES;
            }
            [weakSelf loadBookcaseView];
            [ReaderGlobalModel shareModel].bookshelf = weakSelf.books;
        }];
        
    } failed:^(int stateCode, NSString *failMsg) {
        [_HUD removeFromSuperview];
        [ToastView showMsg:failMsg inView:self.view isCenter:YES];
        if(complete)complete(NO);
    }];
}

-(void)bookcaseView:(BookcaseView *)view clickBookItem:(Book *)book{
    
    [self pushToReader:book];
}

-(void)bookcaseViewClickAddBook:(BookcaseView *)view{
    
    self.tabBarController.selectedIndex = 1;
}

-(void)bookcaseView:(BookcaseView *)view isEditing:(BOOL)isEdit{
    
    self.isEditing = isEdit;
}

- (void)pushToReader:(Book *)book{
    
    UIView *hudView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    hudView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
    MBProgressHUD *HUD = [[MBProgressHUD alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    HUD.labelText = kInfoLocalLoad;
    [HUD show:YES];
    [hudView addSubview:HUD];
    
    double time = 0;
    ReaderBookModel *readerbookModel = [[ReaderBookModel alloc] initWithBook:book isMiddleIn:NO];
    if(![readerbookModel isExistCurrentChapter]){
        HUD.labelText = kInfoNetLoad;
        time = [[NSDate date] timeIntervalSince1970];
    }else if([readerbookModel needUpdateChapterlistFile]){
        HUD.labelText = kInfoNetNewLoad;
    }else{
        HUD.labelText = kInfoLocalLoad;
    }
    [[UIApplication sharedApplication].delegate.window.rootViewController.view addSubview:hudView];//加载到跟视图上，防止用户点击下方的书城切换打开多个阅读界面
    
    [readerbookModel getInitPageDataComplete:^(NSDictionary *dict,TurnResult result) {
        
        NSArray *array = [dict objectForKey:@"data"];
        if(!dict||!array||[array count]==0||result==TurnNoNet){//未获取到内容
            [ToastView showMsg:kContentErrorNoNetInfo inView:self.view isCenter:YES];
            [hudView removeFromSuperview];
            return ;
        }
        
        double inteval = 0.0f;
        if(time>0)inteval = 2.0 - ([[NSDate date] timeIntervalSince1970]-time);
        inteval = inteval<0?0:inteval;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, inteval * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [hudView removeFromSuperview];
            ReaderViewController *reader = [[ReaderViewController alloc] init];
            reader.readerBookModel = readerbookModel;
            [reader loadPageviewDatasource:dict];
            
            [self.navigationController pushViewController:reader animated:YES];
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                //时间戳
                readerbookModel.readerBook.book.readingtime = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
                //网络获取的章节数
                NSString *chaptercount = readerbookModel.readerBook.book.chaptercount;
                readerbookModel.readerBook.book.lasthaptercount = chaptercount;
                [[FmdbAccess shareModel] updateBook:readerbookModel.readerBook.book forceUpdate:YES];
                [self getLocalBooksAndLoadView];//点击阅读之后，当前的最新阅读书籍排到第一位
            });
        });
    }];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
